'use strict';
const {
  Model
} = require('sequelize');
const moment = require('moment');
moment.locale('zh-cn');

module.exports = (sequelize, DataTypes) => {
  class Course extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // 关联模型
      models.Course.belongsTo(models.Category, { as: 'category' });
      models.Course.belongsTo(models.User, { as: 'user' });
      models.Course.hasMany(models.Chapter, { as: 'chapters' });
      // 多对多关联，通过中间表 Like 实现点赞功能
      models.Course.belongsToMany(models.User, {
        through: models.Like,
        foreignKey: 'courseId',
        as: 'likeUsers'
      })
    }
  }
  Course.init({
    categoryId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: { msg: '分类ID必须填写' },
        notEmpty: { msg: '分类ID不能为空' },
        async isPresent(value) {
          const category = await sequelize.models.Category.findByPk(value);
          if (!category) {
            throw new Error(`分类ID ${value}不存在`);
          }
        }
      }
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: { msg: '用户ID必须填写' },
        notEmpty: { msg: '用户ID不能为空' },
        async isPresent(value) {
          const user = await sequelize.models.User.findByPk(value);
          if (!user) {
            throw new Error(`用户ID ${value}不存在`);
          }
        }
      }
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: { msg: '课程名称必须填写' },
        notEmpty: { msg: '课程名称不能为空' }
      }
    },
    image: DataTypes.STRING,
    recommended: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    introductory: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    content: DataTypes.TEXT,
    likesCount: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      defaultValue: 0,
    },
    chaptersCount: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      defaultValue: 0,
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('createdAt')).format('LL');
      },
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return moment(this.getDataValue('updatedAt')).format('LL');
      },
    }
  }, {
    sequelize,
    modelName: 'Course',
  });
  return Course;
};